package com.Teacher.service;

import com.Teacher.mapper.StudentMapper;
import com.Teacher.model.StudentInfo;
import com.model.TeacherInfo;
import jakarta.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created with Intellij IDEA.
 * Description;
 * User:TQ02
 * Data:2024-07-20
 * Time:17:02
 * Text：
 */
@Service
public class StudentService {
    @Autowired
    StudentMapper studentMapper;
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

    // 计时器
    private static AtomicInteger atomicInteger = new AtomicInteger(1);
    private static List<ServiceInstance> instances;

    @PostConstruct
    public void init(){
        //根据应⽤名称获取服务列表
        instances = discoveryClient.getInstances("Teacher-service");
    }
//    public StudentInfo getId(int id){
//        StudentInfo studentInfo = studentMapper.getId(id);
//        //每次都会自增！
//        int index = atomicInteger.getAndIncrement() % instances.size();
//        ServiceInstance instance = instances.get(index);
//        String url = instance.getUri().toString()+"/Teacher/"+studentInfo.getClassroom();
//        TeacherInfo teacherInfo = restTemplate.getForObject(url, TeacherInfo.class);
//        studentInfo.setTeacherInfo(teacherInfo);
//        return studentInfo;
//    }
    public StudentInfo getId(int id){
        StudentInfo studentInfo = studentMapper.getId(id);
        String url = "http://Teacher-service/Teacher/"+studentInfo.getClassroom();
        TeacherInfo teacherInfo = restTemplate.getForObject(url, TeacherInfo.class);
        studentInfo.setTeacherInfo(teacherInfo);
        return studentInfo;
    }
}
